package com.jin.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jin.common.utils.R;
import com.jin.gulimall.cart.feign.ProductFeignService;
import com.jin.gulimall.cart.intercepter.CartInterceptor;
import com.jin.gulimall.cart.service.CartService;
import com.jin.gulimall.cart.vo.Cart;
import com.jin.gulimall.cart.vo.CartItem;
import com.jin.gulimall.cart.vo.ProductCartVo;
import com.jin.gulimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        String res = (String) cartOperations.get(skuId.toString());
        if(StringUtils.isEmpty(res)){
            //购物车里没有添加过该商品
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //获取要添加到购物车中商品的详细信息(远程调用)
                R skuinfo = productFeignService.getSkuinfo(skuId);
                ProductCartVo data = skuinfo.getData("skuInfo", new TypeReference<ProductCartVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setPrice(data.getPrice());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
            }, executor);
            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                //远程调用获取skuSaleAttrValues信息
                List<String> values = productFeignService.getSkuSaleAttrValuesBySkuId(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValuesTask).get();
            //在所有异步任务完成后，将购物车加入缓存中
            String s = JSON.toJSONString(cartItem);
            //此句就是将商品添加到购物车（redis）中
            cartOperations.put(skuId.toString(),s);
            return cartItem;
        }
        else{
            //购物车中添加过该商品，只用修改数量即可
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOperations.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 获取购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOperations();
        String res = (String) operations.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(res, CartItem.class);
        return cartItem;
    }


    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Long userId = userInfoTo.getUserId();
        Cart cart = new Cart();
        if(userId!=null){
            //登录了，需要判断如果临时购物车里有东西，需要合并
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if(tempCartItems!=null&&tempCartItems.size()>0){
                //遍历将临时购物车中的商品加入到在线/用户购物车中
                for (CartItem cartItem : tempCartItems) {
                    //加入的是CART_PREFIX + userId的购物车（threadLocal的作用，获取到了）
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                //添加之后要清空临时购物车
                clearCart(tempCartKey);
            }
            String cartKey = CART_PREFIX + userId;
            List<CartItem> items = getCartItems(cartKey);
            cart.setItems(items);
            return cart;
        }else{
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
            return cart;
        }
    }

    /**
     * 清空购物车数据
     * @param tempCartKey
     */
    public void clearCart(String tempCartKey) {
        redisTemplate.delete(tempCartKey);
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> operations = getCartOperations();
        operations.put(skuId.toString(),s);
    }

    @Override
    public void changeCountItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> hashOperations = getCartOperations();
        hashOperations.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> hashOperations = getCartOperations();
        hashOperations.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            //未登录不做处理，因为当开始创建订单的时候必须是登录状态
            return null;
        }else{
            //登录了,获取选中的购物项，注意商品的价格要实时获取
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().
                    filter(item -> item.getCheck()).
                    map(item->{
                        //更新为最新价格
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                        return item;
                    }).
                    collect(Collectors.toList());
            return collect;
        }
    }

    /**
     * 获取购物车中所有购物项
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if(values!=null&&values.size()>0){
            List<CartItem> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOperations() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Long userId = userInfoTo.getUserId();
        String cartKey = "";
        if(StringUtils.isEmpty(userId)){
            //没有登录
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }else{
            //登录了
            cartKey = CART_PREFIX + userId;
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
